﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZT.Core.Dto;
using ZT.Core.IService;
using ZT.Core.Model;
using ZT.Core.ORM;
using ZT.Core.Utility;

namespace ZT.Core.Service
{
    /// <summary>
    /// 系统日志
    /// </summary>
    public class SysLogService : ServiceBase, ISysLog
    {
        private IUnitOfWork work = null;
        private IRepository<Sys_Log> rpsSysLog=null;
        public SysLogService(IUnitOfWork unitOfWork)
        {
            work = unitOfWork;
            UnitOfWork = work;
            rpsSysLog = work.Repository<Sys_Log>();
        }

        public ResultModel<bool> DelSysLogById(Guid logId)
        {
            try
            {
                var log = rpsSysLog.GetModel(logId);
                if (logId == null)
                {
                    throw new Exception("未找到所需删除项!");
                }
                rpsSysLog.Delete(log);
                work.Commit();
                return new ResultModel<bool>(true);
            }
            catch (Exception ex)
            {
                return new ResultModel<bool>(ex);
            }
        }

        public ResultModel<SysLogModel> GetSysLogById(Guid logId)
        {
            try
            {
                var log = rpsSysLog.GetModel(logId);
                if (logId == null)
                {
                    throw new Exception("未找到所需项!");
                }
                var res = log.MAPTO<SysLogModel>(); 
                return new ResultModel<SysLogModel>(res);
            }
            catch (Exception ex)
            {
                return new ResultModel<SysLogModel>(ex);
            }
        }

        public ResultModel<Pager<SysLogPage>> GetSysLogPages(PagerQuery<SysLogQuery> query)
        {
            try
            {
                var logs = rpsSysLog.Queryable(p => p.LogDate >= query.Query.StartDate && p.LogDate <= query.Query.EndDate && (p.LogUser.Contains(query.Query.KeyWord) || query.Query.KeyWord == string.Empty))
                    .Select(s => new SysLogPage
                    {
                        ClientIP = s.ClientIP,
                        Id = s.Id,
                        LogDate = s.LogDate,
                        LogUser = s.LogUser,
                        Memo = s.Memo,
                        OperateResult = s.OperateResult,
                        RequestAction = s.RequestAction,
                        RequestMethod = s.RequestMethod
                    }).OrderByDescending(o=>o.LogDate);
                var res =new Pager<SysLogPage>().GetCurrentPage(logs,query.PageSize,query.PageIndex) ;
                return new ResultModel<Pager<SysLogPage>>(res);
            }
            catch (Exception ex)
            {
                return new ResultModel<Pager<SysLogPage>>(ex);
            }
        }
    }
}
